package com.yangyang.ralearn.message;

import org.jboss.netty.channel.Channel;

import com.yangyang.ralearn.common.JEnvironment;
import com.yangyang.ralearn.common.exception.ErrorActionException;
import com.yangyang.ralearn.common.exception.ReachGoalException;
import com.yangyang.ralearn.net.message.AbstractReqMessage;
import com.yangyang.ralearn.net.message.Message;
import com.yangyang.ralearn.net.message.MessageFactory;
import com.yangyang.ralearn.net.message.MessageId;
import com.yangyang.ralearn.net.serialize.AutoSerializable;
import com.yangyang.ralearn.server.JSimulator;
import com.yangyang.ralearn.server.ServerManager;

@Message(id = MessageId.REQ_DOACTION)
public class ReqDoActionMessage extends AbstractReqMessage {

	@AutoSerializable(index = 1)
	private String action = "";

	public void init(String action) {
		this.action = action;
	}

	@Override
	public void onGetClientMessage(int id, Channel channel,
			JEnvironment environment, JSimulator simulator) {
		// TODO Auto-generated method stub
		simulator = ServerManager.instance().getSimulatorById(id);
		byte result = 1;
		try {
			simulator.doAction(action);
		} catch (ReachGoalException e) {
			// TODO Auto-generated catch block
			result = 2;
			e.printStackTrace();
		} catch (ErrorActionException e) {
			// TODO Auto-generated catch block
			result = 0;
			// e.printStackTrace();
		}

		RespDoActionMessage message = (RespDoActionMessage) MessageFactory
				.instance().createMessage(MessageId.RESP_DOACTION);
		message.init(action, result);
		ServerManager.instance().sendMessage(id, message, (Integer[]) null);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
